package com.ruoyi.platform.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.platform.domain.*;
import com.ruoyi.platform.domain.request.InspectionLedgerRequest;
import com.ruoyi.platform.domain.vo.InspectionLedgerVo;
import com.ruoyi.platform.exception.BusinessException;
import com.ruoyi.platform.mapper.*;
import com.ruoyi.platform.service.IAsyncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.platform.service.IMExecuteCommandService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

/**
 * 【执行指令】Service业务层处理
 *
 * @author dataControl
 * @date 2025-09-15
 */
@Service
public class MExecuteCommandServiceImpl implements IMExecuteCommandService {
    @Autowired
    private MExecuteCommandMapper mExecuteCommandMapper;

    @Autowired
    private MMonitoringEquipmentMapper monitoringEquipmentMapper;

    @Autowired
    private MStoreLocationMapper storeLocationMapper;

    @Autowired
    private MExecuteCommandResultMapper executeCommandResultMapper;

    @Autowired
    private IAsyncService asyncService;

    @Autowired
    private InspectionLedgerMapper inspectionLedgerMapper;

    private final String platformCommandType = "platform_command_type";

    /**
     * 查询【执行指令】
     *
     * @param commandId 【执行指令】主键
     * @return 【执行指令】
     */
    @Override
    public MExecuteCommand selectMExecuteCommandByCommandId(Long commandId) {
        return mExecuteCommandMapper.selectMExecuteCommandByCommandId(commandId);
    }

    /**
     * 查询【执行指令】列表
     *
     * @param mExecuteCommand 【执行指令】
     * @return 【执行指令】
     */
    @Override
    public List<MExecuteCommand> selectMExecuteCommandList(MExecuteCommand mExecuteCommand) {
        return mExecuteCommandMapper.selectMExecuteCommandList(mExecuteCommand);
    }

    /**
     * 新增【执行指令】
     *
     * @param mExecuteCommand 【执行指令】
     * @return 结果
     */
    @Override
    @Transactional
    public int insertMExecuteCommand(MExecuteCommand mExecuteCommand) throws BusinessException {
        checkSendCommand(mExecuteCommand, false);
        mExecuteCommand.setCommandExecutionStatus(0);//初始为待执行
//        mExecuteCommand.setCommandExecuteTime(DateUtils.getNowDate());
        /**Todo  命令发发送调补全**/
        mExecuteCommand.setContent("硬件连调时应做更正，待完成");
        mExecuteCommandMapper.insertMExecuteCommand(mExecuteCommand);
        /**构建执行结果**/
        MExecuteCommandResult executeCommandResult = new MExecuteCommandResult();
        executeCommandResult.setCommandId(mExecuteCommand.getCommandId().longValue());
        executeCommandResult.setExecuteStartTime(DateUtils.getNowDate());
        executeCommandResult.setExecutionStatus(0);
        executeCommandResultMapper.insertMExecuteCommandResult(executeCommandResult);
        asyncExecuteCommand(executeCommandResult.getCommandResultId(), false);
        return mExecuteCommand.getCommandId().intValue();
    }

    @Override
    public Boolean retrySendCommandByCommandId(Long commandId, Long commandResultId) throws BusinessException {
        MExecuteCommand query = new MExecuteCommand();
        query.setCommandId(commandId);
        query.setCommandResultId(commandResultId);
        List<MExecuteCommand> commandExecuteList = mExecuteCommandMapper.selectMExecuteCommandList(query);
        MExecuteCommand executeCommand = null;
        if (CollectionUtils.isEmpty(commandExecuteList)) {
            throw new BusinessException("指令信息不存在");
        } else {
            executeCommand = commandExecuteList.get(0);
        }
        executeCommand.setCommandResultId(commandResultId);
        checkSendCommand(executeCommand, true);
        /**Todo  命令发发送调补全**/
        executeCommand.setRetryCount(executeCommand.getRetryCount() + 1);
        /**构建执行结果**/
        MExecuteCommandResult executeCommandResult = new MExecuteCommandResult();
        executeCommandResult.setCommandId(executeCommand.getCommandId());
        executeCommandResult.setExecuteStartTime(DateUtils.getNowDate());
        executeCommandResult.setExecutionStatus(0);
        Integer flag = executeCommandResultMapper.insertMExecuteCommandResult(executeCommandResult);
        asyncExecuteCommand(executeCommandResult.getCommandResultId().longValue(), true);
        return flag > 0;
    }

    private void checkSendCommand(MExecuteCommand mExecuteCommand, Boolean isRetrySend) throws BusinessException {
        if (mExecuteCommand.getEquipmentId() == null) {
            throw new BusinessException("设备ID不存在");
        }
        if (mExecuteCommand.getStoreLocationId() == null) {
            throw new BusinessException("仓位ID不存在");
        }
        MMonitoringEquipment equipment = monitoringEquipmentMapper.selectMMonitoringEquipmentByEquipmentId(mExecuteCommand.getEquipmentId());
        MStoreLocation location = storeLocationMapper.selectMStoreLocationByStoreLocationId(mExecuteCommand.getStoreLocationId());
        if (equipment == null) {
            throw new BusinessException("设备不存在");
        }
        if (location == null) {
            throw new BusinessException("仓位不存在");
        }
        if (location.getUseStatus().equals(0L)) {
            throw new BusinessException("仓位状态为未启用");
        }
        if (equipment.getUseStatus().equals(0L)) {
            throw new BusinessException("设备状态为未启用");
        }
        if (isRetrySend) {
            MExecuteCommandResult commandResult = executeCommandResultMapper.selectMExecuteCommandResultByCommandResultId(mExecuteCommand.getCommandResultId());
            if (commandResult == null) {
                throw new BusinessException("指令执行结果信息不存在");
            }
            mExecuteCommand.setExecuteCommandResult(commandResult);
            mExecuteCommand.setLocation(location);
            mExecuteCommand.setEquipment(equipment);
        }
    }

    /**
     * 修改【执行指令】
     *
     * @param mExecuteCommand 【执行指令】
     * @return 结果
     */
    @Override
    public int updateMExecuteCommand(MExecuteCommand mExecuteCommand) {
        return mExecuteCommandMapper.updateMExecuteCommand(mExecuteCommand);
    }

    /**
     * 批量删除【执行指令】
     *
     * @param commandIds 需要删除的【执行指令】主键
     * @return 结果
     */
    @Override
    public int deleteMExecuteCommandByCommandIds(Long[] commandIds) {
        return mExecuteCommandMapper.deleteMExecuteCommandByCommandIds(commandIds);
    }

    /**
     * 删除【执行指令】信息
     *
     * @param commandId 【执行指令】主键
     * @return 结果
     */
    @Override
    public int deleteMExecuteCommandByCommandId(Long commandId) {
        return mExecuteCommandMapper.deleteMExecuteCommandByCommandId(commandId);
    }

    /**
     * 自动巡检指令执行
     */
    @Override
    public void automaticInspection() {
        InspectionLedgerRequest request = new InspectionLedgerRequest();
        request.setInspectionStatus(1);
        request.setEquipmentUseInspection(1L);
        request.setStoreUseInspection(1L);
        List<InspectionLedgerVo> list = inspectionLedgerMapper.selectInspectionLedgerList(request);
        List<MExecuteCommandResult> resultList = new ArrayList<>();
        list.forEach(item -> {
            MExecuteCommand command = new MExecuteCommand();
            command.setEquipmentId(item.getEquipmentId());
            command.setStoreLocationId(item.getStoreLocationId());
            command.setStoreLocationCode(item.getStoreLocationCode());
            command.setCommandType(3);
            command.setCommandExecutionStatus(0);
            command.setRetryCount(0);
            mExecuteCommandMapper.insertMExecuteCommand(command);
            MExecuteCommandResult result = new MExecuteCommandResult();
            result.setCommandId(command.getCommandId());
            result.setExecutionStatus(0);
            result.setCreateDate(DateUtils.getNowDate());
            executeCommandResultMapper.insertMExecuteCommandResult(result);
            resultList.add(result);
        });
        if (!CollectionUtils.isEmpty(resultList)) {
            resultList.forEach(item -> {
                asyncExecuteCommand(item.getCommandResultId(), false);
            });
        }
    }

    /**
     * 调用异步执行指令
     *
     * @param commandResultId
     * @param isRetrySend
     */
    private void asyncExecuteCommand(Long commandResultId, Boolean isRetrySend) {
        /**获取当前登录用户信息**/
        LoginUser loginUser = null;
        try {
            loginUser = SecurityUtils.getLoginUser();
        } catch (Exception ex) {
        }
        asyncService.executeAsyncExecuteCommand(commandResultId, isRetrySend, loginUser);
    }
}
